package com.yc.qunxing.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.yc.qunxing.common.AlipayTradePagePay;
import com.yc.qunxing.common.AlipayTradePrecreate;
import com.yc.qunxing.common.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("/pay")
@Slf4j
public class PayController {

    // 电脑端网页支付
    @GetMapping
    public String pagePay(@RequestParam("total_amount") String total) {
        Order content = new Order();
        content.setTotal_amount(total);

        log.info("Total amount received: {}", total);

        try {
            /** 获取接口调用结果 **/
            AlipayTradePagePayResponse payResponse = AlipayTradePagePay.pay(content);
            String responseBody = payResponse.getBody();
            log.info(responseBody);
            return responseBody;
        } catch (AlipayApiException e) {
            log.error("Error occurred during Alipay page pay process", e);
            throw new RuntimeException(e);
        }
    }

    @PostMapping
    public String precreatePay(@RequestParam("total_amount") String total, HttpSession session) {
        Order content = new Order();
        content.setTotal_amount(total);

        try {
            /** 获取接口调用结果 **/
            AlipayTradePrecreateResponse payResponse = AlipayTradePrecreate.pay(content);
            log.info("Response Body: {}", payResponse.getBody());
            log.info("QR Code: {}", payResponse.getQrCode());
            session.setAttribute("qccode", payResponse.getQrCode());
            return payResponse.getQrCode();
        } catch (AlipayApiException e) {
            log.error("Error occurred during Alipay precreate pay process", e);
            throw new RuntimeException(e);
        }
    }
}
